﻿using Aliyun.OSS;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace DTcms.Core.Common.Helper
{
    /// <summary>
    /// 阿里云OSS帮助类
    /// </summary>
    public class OssHelper
    {
        /// <summary>
        /// 普通文件上传
        /// </summary>
        public static bool UploadFile(byte[] byteData, string? endpoint, string? accessKey, string? secretKey, string? bucketName, string? fileName)
        {
            var client = new OssClient(endpoint, accessKey, secretKey);
            using (Stream fileStream = new MemoryStream(byteData))
            {
                string md5 = Aliyun.OSS.Util.OssUtils.ComputeContentMd5(fileStream, byteData.Length);
                try
                {
                    //将文件md5值赋值给meat头信息，服务器验证文件MD5  
                    var objectMeta = new Aliyun.OSS.ObjectMetadata
                    {
                        ContentMd5 = md5,
                    };
                    //文件上传--空间名、文件保存路径、文件流、meta头信息(文件md5)
                    client.PutObject(bucketName, fileName, fileStream, objectMeta);
                    return true;
                }
                catch (Exception e)
                {
                    throw new ResponseException(e.Message);
                }
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        public static bool DeleteFile(string? endpoint, string? accessKey, string? secretKey, string? bucketName, string? fileName)
        {
            var client = new OssClient(endpoint, accessKey, secretKey);
            try
            {
                client.DeleteObject(bucketName, fileName);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
